<?php

namespace app\admin\controller;

use app\admin\model\film\Info as FilmInfo;
use app\admin\model\Hall;
use app\admin\model\Schedule as ScheduleModel;
use app\common\controller\Backend;
use app\common\model\OrderTicket;
use app\admin\model\Order;
use PHPQRCode\QRcode;
use PhpOffice\PhpWord\TemplateProcessor;
use think\exception\DbException;
use think\Log;
use think\response\Json;

/**
 * 订单票据
 *
 * @icon fa fa-circle-o
 */
class Ticket extends Backend
{

    /**
     * Ticket模型对象
     * @var \app\admin\model\Ticket
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->assignconfig('order_id',$this->request->request('order_id'));
        $this->view->assign('order_id', $this->request->request('order_id'));
        $this->model = new \app\admin\model\Ticket;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $order_id = $this->request->param('order_id');
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model
            ->whereIn('status',[1])
            ->where($where)
            ->where('order_id',$order_id)
            ->order($sort, $order)
            ->paginate($limit);
//        if ($list){
//            foreach ($list as $key=>&$value)
//            {
//                $value['x_coord_text'] = ($value['x_coord']+1).'排';
//                $value['y_coord_text'] = ($value['y_coord']+1).'列';
//            }
//        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /*
     * 打印小票
     * */
    public function print()
    {
        $ticket_id = $this->request->param('ticket_id');

        $order_ticket_info = $this->model->where('id',$ticket_id)->find();
        $order_info = Order::where(['id'=>$order_ticket_info['order_id']])->find();
        $hall = Hall::where(['id'=>$order_info['hall_id']])->find();
        $film_info = FilmInfo::where(['id'=>$order_info['film_info_id']])->find();
        $schedules = ScheduleModel::where(['id'=>$order_info['schedule_id']])->find();

        $ticket_info['sn'] = $order_info['sn'];
        $ticket_info['hall_name'] = $hall['name'];
        $ticket_info['film_name'] = $film_info['name'];
        $ticket_info['start_date'] = $schedules['date'];
        $ticket_info['start_time'] = $schedules['start_time'];
        $ticket_info['seat_text'] =  $order_ticket_info['row_num'].'排'.$order_ticket_info['column_num'].'座';
        $ticket_info['seat_price'] =  $order_ticket_info['seat_price'];
        $seat_type = $order_ticket_info['seat_type']=='normal'?'普通座':'舒适座';
        $ticket_info['seat_type'] =  $seat_type;
        $ticket_info['docx_name'] =$order_info['sn'].'_'.$order_ticket_info['x_coord'].'_'.$order_ticket_info['y_coord'];
        $ticket_info['qrcode_path'] = $order_ticket_info['qrcode_path'];
        $ticket_info['ticket_path'] = $this->setContractContentWorld($ticket_info);
        Log::info('打印小票word');
        Log::info($ticket_info['ticket_path']);
        return $this->view->fetch('',['order_info'=>$order_info,'ticket_info'=>$ticket_info]);
    }

    public function update_order_status($order_id)
    {
        $order_info = $this->model->where('id',$order_id)->find();
        if($order_info['status']=='1')
        {
            $this->model->where('id',$order_info['id'])->setField('status','2');
            OrderTicket::where(['status'=>1,'order_id'=>$order_id])->update(['status'=>2]);
        }
    }

    /**
     * 生成小票world文件
     */
    public function setContractContentWorld($params)
    {

        $tmp = new TemplateProcessor('ticket_template.docx');
//        $qrcode_path = $this->scerweima($params['sn']);
        $tmp->setValue('sn',$params['sn']);
        $tmp->setValue('hall_name',$params['hall_name']);
        $tmp->setValue('film_name',$params['film_name']);
        $tmp->setValue('start_date',$params['start_date']);
        $tmp->setValue('start_time',$params['start_time']);
        $tmp->setValue('seat_text',$params['seat_text']);
        $tmp->setValue('seat_price',$params['seat_price']);
        $tmp->setValue('seat_type',$params['seat_type']);
        $tmp->setImageValue('qrcode',["path" => $params['qrcode_path'], "width" =>'100', "height" =>'100']);

        $date = date('Ymd');
        $dir = '/uploads/ticket/'.$date;
        if(!is_dir($dir)){
            @mkdir('.'.$dir,0777,true);
        }

        $filename = $dir.'/'.$params['docx_name'].'.docx';
//        var_dump($filename);
        $tmp->saveAs('.'.$filename);//另存为
//        return $res;
        return compatImage($filename);
//        return ['full_path'=>compatImage($filename),'relative_path'=>$filename];
    }

    //生成二维码
    //2. 在生成的二维码中加上logo(生成图片文件)
    public function scerweima($text){
        //echo 'hee';die;
        // dump(APP_XCF_LOG.'xcf.png');die;
        //Vendor('chillerlan.php-qrcode.public.qrcode');
        //$pathname = date("Ymd",time());
        $pathname = APP_PATH . '/../public/uploads/qrcode/';
        if(!is_dir($pathname)) { //若目录不存在则创建之
            mkdir($pathname,0777,true);
        }

        $errorCorrectionLevel = 'H';  //容错级别
        $matrixPointSize = 10;      //生成图片大小
        //生成二维码图片
        $abc = $text.'.png';
        $filename = $pathname.$abc;

        if (file_exists($filename)){
            return request()->domain().'/uploads/qrcode/'.$abc;
        }
        $url = request()->domain() ."?no=" . $text;
        QRcode::png($text,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
//        $logo = APP_PATH . '/../public/assets/xcf_log/xcf.png'; //准备好的logo图片
        // dump(APP_XCF_LOG.'xcf.png');die;
        //dump($logo);die;
        $QR = $filename;      //已经生成的原始二维码图
        // dump($QR);
//        if (file_exists($logo)) {
//            $QR = imagecreatefromstring(file_get_contents($QR));    //目标图象连接资源。
//            $logo = imagecreatefromstring(file_get_contents($logo));  //源图象连接资源。
//            $QR_width = imagesx($QR);      //二维码图片宽度
//            $QR_height = imagesy($QR);     //二维码图片高度
//            $logo_width = imagesx($logo);    //logo图片宽度
//            $logo_height = imagesy($logo);   //logo图片高度
//            $logo_qr_width = $QR_width / 4;   //组合之后logo的宽度(占二维码的1/5)
//            $scale = $logo_width/$logo_qr_width;  //logo的宽度缩放比(本身宽度/组合后的宽度)
//            $logo_qr_height = $logo_height/$scale; //组合之后logo的高度
//            $from_width = ($QR_width - $logo_qr_width) / 2;  //组合之后logo左上角所在坐标点
//            //重新组合图片并调整大小
//            /*
//             * imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中
//             */
//            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
//        }
        //输出图片
//        imagepng($QR,$filename);

        return request()->domain().'/uploads/qrcode/'.$abc;
    }
}
